﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace SGWSearchTool
{
    public partial class MainForm : Form
    {
        private StartSearchClass m_SearchThreadClass = null; 

        private SetIPForm m_SetIPForm = null;

        //搜索命令
        private string m_SearchCmd = "";

        private int m_DeviceCount = 0;

        public MainForm()
        {
            InitializeComponent();

            //加载IP
            LoadLocalIP();

            //加载搜索命令
            LoadSearchSGWCmd();
        }

        public string GetSearcheCmd()
        {
            return m_SearchCmd;
        }

        private void btsearch_Click(object sender, EventArgs e)
        {
            if (LocalIPComBox.Text.Length == 0 || SearchPortTxtBox.Text.Length == 0 || 
                TimesTextBox.Text.Length == 0)
            {
                MessageBox.Show("请选择本机IP地址和输入扫描端口！", "提示",
                                MessageBoxButtons.OK,//定义对话框的按钮
                                MessageBoxIcon.Error,//定义对话框内的图表式样，这里是一个黄色三角型内加一个感叹号 
                                MessageBoxDefaultButton.Button1);//定义对话框的按钮式样
                return;
            }

            if (m_SearchCmd.Length == 0)
            {
                MessageBox.Show("搜索命令不存在,请安装搜索命令！", "提示",
                                MessageBoxButtons.OK,//定义对话框的按钮
                                MessageBoxIcon.Error,//定义对话框内的图表式样，这里是一个黄色三角型内加一个感叹号 
                                MessageBoxDefaultButton.Button1);//定义对话框的按钮式样
                return;
            }

            //清除之前内容
            this.ResultTxtBox.Text = "";
            this.SGWListDataGridView.Rows.Clear();

            btsearch.Enabled = false;
            btStop.Enabled = true;
            m_DeviceCount = 0;

            //启动定时器
            timer1.Enabled = true;
            timer1.Interval = 500;
            timer1.Start();

            //启动线程
            m_SearchThreadClass = new StartSearchClass();
            m_SearchThreadClass.m_RefreshResult = new StartSearchClass.RefreshResultDelegate(RefreshReusult);
            m_SearchThreadClass.m_RefreshStatus = new StartSearchClass.RefreshStopStatus(RefreshStopStatus);

            string cmdarg = "searchsgw -l " + LocalIPComBox.Text + " -p " + SearchPortTxtBox.Text + " -t " + TimesTextBox.Text;

            m_SearchThreadClass.StartThead(m_SearchCmd, cmdarg);

            return;
        }

        private void RefreshReusult(String log)
        {
            /*判断该方法是否被主线程调用，也就是创建labMessage1控件的线程，当控件的InvokeRequired属性为ture时，
             * 说明是被主线程以外的线程调用。如果不加判断，会造成异常*/
            if (this.ResultTxtBox.InvokeRequired)
            {
                //再次创建一个TestClass类的对象 
                StartSearchClass searchclass = new StartSearchClass();

                //为新对象的mainThread对象搭载方法 
                searchclass.m_RefreshResult = new StartSearchClass.RefreshResultDelegate(RefreshReusult);

                //this指窗体，在这调用窗体的Invoke方法，也就是用窗体的创建线程来执行mainThread对象委托的方法，再加上需要的参数(i) 
                if (log == null)
                {
                    this.Invoke(searchclass.m_RefreshResult, new object[] { "Search Finish." });  
                }
                else
                {
                    this.Invoke(searchclass.m_RefreshResult, new object[] { log });  
                }        
            }
            else
            {
                if (log.IndexOf("Search Finish") > -1)
                {
                    btsearch.Enabled = true;
                    btStop.Enabled = false;
                    ResultTxtBox.AppendText("\r\n" + log + "\r\n");
                }
                else if (log.Length > 0 && log.IndexOf("Any key contiue") == -1)
                {
                    ResultTxtBox.AppendText("\r\n" + log + "\r\n");
                    if (log.IndexOf("SGW") >= 0)
                    {
                        AddDeviceToTable(log);
                    }
                }
            }
        }

        private void RefreshStopStatus()
        {
            /*判断该方法是否被主线程调用，也就是创建labMessage1控件的线程，当控件的InvokeRequired属性为ture时，
             * 说明是被主线程以外的线程调用。如果不加判断，会造成异常*/
            if (this.ResultTxtBox.InvokeRequired)
            {
                //再次创建一个TestClass类的对象 
                StartSearchClass searchclass = new StartSearchClass();

                //为新对象的mainThread对象搭载方法 
                searchclass.m_RefreshStatus = new StartSearchClass.RefreshStopStatus(RefreshStopStatus);

                //this指窗体，在这调用窗体的Invoke方法，也就是用窗体的创建线程来执行mainThread对象委托的方法，再加上需要的参数(i) 
                this.Invoke(searchclass.m_RefreshStatus);
            }
            else
            {
                this.ResultTxtBox.Text = "Start search...\r\n";
                this.timer1.Enabled = false;
                this.timer1.Stop(); 
            }
        }

        /// <summary>
        /// 获取本机IP地址
        /// </summary>
        /// <returns>本机IP地址</returns>
        public void LoadLocalIP()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        LocalIPComBox.Items.Add(IpEntry.AddressList[i].ToString());
                        //return IpEntry.AddressList[i].ToString();
                    }
                }

                if (LocalIPComBox.Items.Count > 0)
                {
                    LocalIPComBox.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载本机IP地址失败！" + ex.Message, "警告",
                                MessageBoxButtons.OK,//定义对话框的按钮
                                MessageBoxIcon.Warning,//定义对话框内的图表式样，这里是一个黄色三角型内加一个感叹号 
                                MessageBoxDefaultButton.Button1);//定义对话框的按钮式样
            }
        }

        private void LoadSearchSGWCmd()
        {
            string workingFolder = System.IO.Directory.GetCurrentDirectory();
            string patchsgwcmd = workingFolder + "\\sgwcmd\\" + "sgwcmd.exe";

            //判断文件的存在
            if (File.Exists(patchsgwcmd))
            {
                //存在文件
                m_SearchCmd = patchsgwcmd;
            }
            else
            {
                patchsgwcmd = workingFolder + "\\sgwcmd\\" + "sgwcmdd.exe";
                if (File.Exists(patchsgwcmd))
                {
                    //存在文件
                    m_SearchCmd = patchsgwcmd;
                }
            }

            return;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.ResultTxtBox.Text == "Start search......")
            {
                this.ResultTxtBox.Text = "Start search.";
            }
            else
            {
                if (this.ResultTxtBox.Text.Length == 0)
                {
                    this.ResultTxtBox.Text += "Start search.";
                }
                else
                {
                    this.ResultTxtBox.Text += ".";
                }
            }
            
        }

        //添加设备到表格
        private void AddDeviceToTable(String log)
        {
            m_DeviceCount++;

            string[] logarr = log.Split(';');
            string[] sgwname = logarr[0].Split(':');
            string[] sgwsn = logarr[1].Split(':');
            string[] sgwtype = logarr[2].Split(':');

            string netstr = "";
            for (int i = 3; i < logarr.Length; i++)
            {
                if (netstr != "")
                {
                    netstr = netstr + "|" +logarr[i];
                }
                else
                {
                    netstr = logarr[i];
                }
            }

            int index = this.SGWListDataGridView.Rows.Add();
            this.SGWListDataGridView.Rows[index].HeaderCell.Value = m_DeviceCount.ToString();
            this.SGWListDataGridView.Rows[index].Cells[0].Value = sgwname[1];
            this.SGWListDataGridView.Rows[index].Cells[1].Value = sgwtype[1];
            this.SGWListDataGridView.Rows[index].Cells[2].Value = sgwsn[1];
            this.SGWListDataGridView.Rows[index].Cells[3].Value = netstr;
        }

        private void btStop_Click(object sender, EventArgs e)
        {
            m_SearchThreadClass.StopThead();
            MessageBox.Show("停止成功！", "提示",
                            MessageBoxButtons.OK,//定义对话框的按钮
                            MessageBoxIcon.Information,//定义对话框内的图表式样，这里是一个黄色三角型内加一个感叹号 
                            MessageBoxDefaultButton.Button1);//定义对话框的按钮式样

            btStop.Enabled = false;
            btsearch.Enabled = true;
        }

        private void SearchPortTxtBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
            {
                MessageBox.Show("请输入数字！", "警告",
                                MessageBoxButtons.OK,//定义对话框的按钮
                                MessageBoxIcon.Error,//定义对话框内的图表式样，这里是一个黄色三角型内加一个感叹号 
                                MessageBoxDefaultButton.Button1);//定义对话框的按钮式样   
                e.Handled = true;
            }
        }

        private void TimesTextBox_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && e.KeyChar != '\b')
            {
                MessageBox.Show("请输入数字！", "警告",
                                MessageBoxButtons.OK,//定义对话框的按钮
                                MessageBoxIcon.Error,//定义对话框内的图表式样，这里是一个黄色三角型内加一个感叹号 
                                MessageBoxDefaultButton.Button1);//定义对话框的按钮式样   
                e.Handled = true;
            }
        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex == 3)
            {
                string ethinfo = this.SGWListDataGridView.Rows[e.RowIndex].Cells[3].Value.ToString();
                string[] etharry = ethinfo.Split('|');
                foreach (string eth in etharry)
                {
                    string[] tmpetharry = eth.Split(':');
                    if (tmpetharry.Length > 1)
                    {
                        System.Diagnostics.Process.Start("http://" + tmpetharry[1]);
                    }
                }
            }
            else
            {
                if (m_SetIPForm == null)
                {
                    m_SetIPForm = new SetIPForm(this);
                }

                m_SetIPForm.ShowDialog();
            }
        }
    }
}
